package com.jpa.web.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Created by BKWJA on 2018/10/25.
 * JDBC工具类：
 * 1、获取connection
 * 2、释放资源
 */
public class JDBCUtils {

    /**
     * 获取Connection
     * @return 所获得到的JDBC的Connection
     */
    public static Connection getConnection() throws Exception{

        /**
         * 不建议大家把配置硬编码到代码中
         *
         * 最佳实践：配置性的建议写到配置文件中
         */
//        String url = "jdbc:mysql://localhost:3306/leecx?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true";
//        String user = "root";
//        String password = "123456";
//        String dirverClass = "com.mysql.jdbc.Driver";

        //引用配置文件
        InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        String url = properties.getProperty("jdbc.url");
        String user = properties.getProperty("jdbc.user");
        String password = properties.getProperty("jdbc.password");
        String dirverClass = properties.getProperty("jdbc.driverClass");

        Class.forName(dirverClass);
        Connection connection = DriverManager.getConnection(url,user,password);
        return connection;
    }

    /**
     * 释放dbbc相关的资源
     * @param rs
     * @param st
     * @param conn
     */
    public static void release(ResultSet rs, Statement st,Connection conn){

        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
